package networking;

import java.util.concurrent.Callable;

import com.jme.util.GameTaskQueueManager;

import interfaces.menu.joinGame.JoinGameContent;
import interfaces.menu.joinGame.filters.Filter;
import interfaces.menu.joinGame.gamesTable.GamesTable;
import interfaces.menu.joinGame.gamesTable.GamesTableWidget;

public class GameInfoBuilder extends Thread {
	
	private String[] ips;
	private GamesTable gamesTable;
	private boolean abort;
	private JoinGameContent joinGameWindow;
	private GameInfoCreator infoCreator;
	private int progress;
	
	public GameInfoBuilder(String[] ips, GamesTable gamesTable, JoinGameContent joinGameWindow) {
		super();
		this.ips = ips;
		this.gamesTable = gamesTable;
		this.joinGameWindow = joinGameWindow;
		
		infoCreator = new GameInfoCreator();
		
		abort = false;
	}
	
	@Override
	public void run() {
		progress = 1;
		for(int i = 0; i < ips.length; i++, progress++) {
			if(abort) break;
			String ip = ips[i];
			if(ip == null) continue;
			
			final GamesTableWidget widget = infoCreator.createWidget(ip);
			if(widget != null && passesFilters(widget)) {
				GameTaskQueueManager.getManager().update(new Callable<Void>() {
					@Override
					public Void call() throws Exception {
						joinGameWindow.updateProgress(progress);
						gamesTable.addGame(widget);
						return null;
					}
				});
			} else {
				GameTaskQueueManager.getManager().update(new Callable<Void>() {
					@Override
					public Void call() throws Exception {
						joinGameWindow.updateProgress(progress);
						return null;
					}
				});
			}
		}
		
		joinGameWindow.finishSearch();
	}
	
	private boolean passesFilters(GamesTableWidget tableWidget) {
		for(Filter f : joinGameWindow.getFilters()) {
			if(!f.passes(tableWidget)) return false;
		}
		return true;
	}
	
	public void abort() { abort = true; }
}